﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace ModernShopping.AppCode
{
    public class DbProductStore
    {
        public static bool AddOrDelete(int ProductCode, List<Store> listStores)
        {
            try
            {
                ModernShoppingDataContext db = new ModernShoppingDataContext();
                foreach (Store st in listStores)
                {
                    int CodeStore = st.Code;
                    if (!db.ProductStores.Any(c => (c.CodeStore.Equals(CodeStore) && c.ProductCode.Equals(ProductCode))))
                    {
                        ProductStore ps = new ProductStore();
                        ps.ProductCode = ProductCode;
                        ps.CodeStore = st.Code;
                        db.ProductStores.InsertOnSubmit(ps);
                    }
                }
                foreach (ProductStore ps in db.ProductStores.Where(c => c.ProductCode.Equals(ProductCode)))
                {
                    if (!listStores.Any(c => (c.Code.Equals(ps.CodeStore))))
                    {
                        db.ProductStores.DeleteOnSubmit(ps);
                    }
                }
                db.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static void initGridviewByStore(GridView gv, int CodeStore)
        {
            ModernShoppingDataContext db = new ModernShoppingDataContext();
            var results = db.ProductStores
                            .Where(c => c.CodeStore.Equals(CodeStore))
                            .Select(c =>
                                new
                                {
                                    Name = c.Product.Name,
                                    Price = c.Product.Price,
                                    ProductCode = c.ProductCode,
                                    CodeStore = c.CodeStore
                                });
            gv.DataSource = results;
            gv.DataBind();
        }

        public static bool Delete(int ProductCode, int CodeStore)
        {
            try
            {
                ModernShoppingDataContext db = new ModernShoppingDataContext();
                var result = db.ProductStores.Where(c =>
                        c.ProductCode.Equals(ProductCode) &&
                        c.CodeStore.Equals(CodeStore)).First();
                db.ProductStores.DeleteOnSubmit(result);
                db.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}